from django.shortcuts import render, redirect, reverse
from django.views import View
from django.contrib.auth import logout

from .forms import RegisterForm, LoginForm
from utils.res_code import json_response, Code
from .models import User

class LoginView(View):
    """
    登录视图
    url： /user/login/
    """
    def get(self, request):
        return render(request, 'user/login.html')

    def post(self, request):
        # 1.先校验
        form = LoginForm(request.POST, request=request)
        if form.is_valid():

            return json_response(errmsg='恭喜登录成功！')
        else:
            # 将表单的报错信息进行拼接
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])

            err_msg_str = '/'.join(err_msg_list)
            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)

class RegisterView(View):
    """
    注册视图
    url:'/user/register/'
    """
    def get(self, request):
        return render(request, 'user/register.html')

    def post(self, request):
        # 1.校验数据
        form = RegisterForm(request.POST)
        if form.is_valid():
            # 创建数据
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            mobile = form.cleaned_data.get('mobile')
            # create_user方法会将密码进行加密创建
            User.objects.create_user(username=username, password=password, mobile=mobile)
            return json_response(errmsg='恭喜你，注册成功！')
        else:
            # 定义一个错误信息列表，将表单错误数据进行拼接
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])
            err_msg_str = '/'.join(err_msg_list)

            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)

class LogoutView(View):
    def get(self, request):
        logout(request)

        return redirect(reverse('user:login'))

